// 这是数据分析页面的js
document.addEventListener('DOMContentLoaded', function() {
    // 从localStorage中获取菜单数据
    const storedMenus = localStorage.getItem('menus');
    
    if (storedMenus) {
        // 用户已登录，发送新的请求
        fetchUserData().then(data => {
            updateDashboardData(data);
        }).catch(error => {
            console.error('获取数据失败:', error);
        });
    } else {
        console.error('没有找到存储在本地的菜单数据，请先登录并获取菜单数据。');
    }
});

function fetchUserData() {
    // 返回 Promise
    return new Promise((resolve, reject) => {
        const url = config.infoip;
        const params = new URLSearchParams({
            method: 'onlineinfo',
        });

        fetch(url + '?' + params, {  
            method: 'GET',  
			credentials: 'include',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.json())
        .then(data => {
            console.log('获取到的数据:', data);
            resolve(data); // 解析 Promise 并返回数据
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            reject(error); // 返回错误
        });
    });
}

// 添加分类名称转换函数
function getCategoryDisplayName(category) {
    const nameMap = {
        '前端方向': '前端开发',
        '后端方向': '后端开发',
        '中端方向': '中端开发'
    };
    return nameMap[category] || category;
}

// 修改渲染饼图函数
function renderCourseCategoryChart(data, selectedCategory) {
    const chartContainer = document.getElementById('courseCategoryChart');
    if (!chartContainer) return;

    // 初始化 ECharts 实例
    const myChart = echarts.init(chartContainer);

    // 准备数据
    let chartData;
    if (selectedCategory === 'all') {
        // 显示所有主要方向的数据（percentage中的数据）
        chartData = Object.entries(data.percentage || {}).map(([key, value]) => ({
            value: parseFloat(value),
            name: getCategoryDisplayName(key)
        }));
    } else {
        // 显示选中方向的具体技术占比（从subjectPercentage中获取数据）
        const subjectData = data.subjectPercentage?.[selectedCategory];
        if (subjectData) {
            chartData = Object.entries(subjectData).map(([key, value]) => ({
                value: parseFloat(value),
                name: key
            }));
        } else {
            // 如果没有找到对应的细分数据，则显示主方向的数据
            chartData = [{
                value: parseFloat(data.percentage?.[selectedCategory] || 0),
                name: getCategoryDisplayName(selectedCategory)
            }];
        }
    }

    // 配置项
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c}%'
        },
        legend: {
            orient: 'vertical',
            right: '10%',
            top: 'center',
            itemWidth: 10,
            itemHeight: 10,
            textStyle: {
                fontSize: 12
            }
        },
        series: [{
            name: '课程分类',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['40%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: true,
                formatter: '{b}: {c}%'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '14',
                    fontWeight: 'bold'
                }
            },
            data: chartData
        }]
    };

    myChart.setOption(option);
    
    // 监听窗口大小变化
    window.addEventListener('resize', function() {
        myChart.resize();
    });
}

function updateDashboardData(data, selectedPeriod = '近1周') {
    // 更新统计数据
    const statsElements = document.querySelectorAll('.youxiashang div p:last-child');
    
    if (statsElements.length >= 4) {
        statsElements[0].textContent = data.totalUser || '0';
        statsElements[1].textContent = data.onlineUser || '0';
        statsElements[2].textContent = data.totalCourses || '0';
        statsElements[3].textContent = Number(data.totalProfit).toFixed(2) || '0';
    }

      // 处理并显示销售趋势图
	if (selectedPeriod === '近1月' && data.trendsmonth) {
		// 处理月度数据
		renderMonthSalesTrendChart(data.trendsmonth[0]); // 使用 trendsmonth 数组的第一个对象
	} else if (data.trendsweek && data.trendsweek.length > 0) {
		// 周数据的处理保持不变
		const weekNumbers = data.trendsweek.map(week => week.week_number);
		const maxWeek = Math.max(...weekNumbers);
		const minWeek = Math.min(...weekNumbers);
		
		let targetWeek;
		if (selectedPeriod === '近1周' || selectedPeriod === undefined) {
			targetWeek = data.trendsweek.find(week => week.week_number === maxWeek);
		} else if (selectedPeriod === '上一周') {
			targetWeek = data.trendsweek.find(week => week.week_number === minWeek);
		}
		
		if (targetWeek) {
			renderSalesTrendChart(targetWeek);
		}
	}


	// 渲染课程分类占比图
	if (data.percentage || data.subjectPercentage) {
		// 传递完整的数据对象，包含 percentage 和 subjectPercentage
		updateCategorySelect(data);
		// 默认显示全部数据的饼图
		renderCourseCategoryChart(data, 'all');
	}
}

// 修改更新下拉框选项的函数
function updateCategorySelect(data) {
    const categorySelect = document.querySelector('.trend-container:nth-child(2) select');
    if (!categorySelect) return;

    // 生成下拉框选项
    let options = '<option value="all">全部</option>';
    
    // 添加主要方向选项
    if (data.percentage) {
        Object.keys(data.percentage).forEach(category => {
            options += `<option value="${category}">${getCategoryDisplayName(category)}</option>`;
        });
    }

    categorySelect.innerHTML = options;

    // 添加change事件监听器
    categorySelect.addEventListener('change', function(e) {
        const selectedCategory = e.target.value;
        renderCourseCategoryChart(data, selectedCategory);
    });
}


// 添加分类名称转换函数
function getCategoryDisplayName(category) {
    const nameMap = {
        '前端方向': '前端开发',
        '后端方向': '后端开发',
        '中端方向': '中端开发'
    };
    return nameMap[category] || category;
}

function renderSalesTrendChart(weekData) {
    // 直接获取图表容器
    const chartContainer = document.getElementById('salesTrendChart');
    if (!chartContainer) return;

    // 准备数据
    const labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    const values = [
        weekData.monday || 0,
        weekData.tuesday || 0,
        weekData.wednesday || 0,
        weekData.thursday || 0,
        weekData.friday || 0,
        weekData.saturday || 0,
        weekData.sunday || 0
    ];

    // 初始化 ECharts 实例
    const myChart = echarts.init(chartContainer);

    // 配置项
    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                return `${params[0].name}<br/>销售额: ￥${params[0].value.toFixed(2)}`;
            }
        },
        grid: {
            top: '10%',
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: labels,
            axisLine: {
                lineStyle: {
                    color: '#999'
                }
            }
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '￥{value}'
            },
            axisLine: {
                lineStyle: {
                    color: '#999'
                }
            },
            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            }
        },
        series: [{
            name: '销售额',
            type: 'line',
            smooth: true,
            data: values,
            itemStyle: {
                color: '#1890ff'
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(24,144,255,0.3)'
                }, {
                    offset: 1,
                    color: 'rgba(24,144,255,0.1)'
                }])
            }
        }]
    };

    // 使用配置项设置图表
    myChart.setOption(option);

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', function() {
        myChart.resize();
    });
}

// 添加月度数据渲染函数
// 修改月度数据渲染函数
function renderMonthSalesTrendChart(monthData) {
    const chartContainer = document.getElementById('salesTrendChart');
    if (!chartContainer) {
        console.error('无法获取销售趋势图容器');
        return;
    }

    // 准备月度数据
    const months = [
        'January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'
    ];
    
    // 将英文月份转换为中文
    const monthNameMap = {
        'January': '1月',
        'February': '2月',
        'March': '3月',
        'April': '4月',
        'May': '5月',
        'June': '6月',
        'July': '7月',
        'August': '8月',
        'September': '9月',
        'October': '10月',
        'November': '11月',
        'December': '12月'
    };

    // 准备图表数据
    const chartData = months.map(month => ({
        name: monthNameMap[month],
        value: monthData[month] || 0
    }));

    // 初始化 ECharts 实例
    const myChart = echarts.init(chartContainer);

    // 配置项
    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                return `${params[0].name}<br/>销售额: ￥${params[0].value.toFixed(2)}`;
            }
        },
        grid: {
            top: '10%',
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: chartData.map(item => item.name),
            axisLabel: {
                interval: 0,
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '￥{value}'
            },
            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            }
        },
        series: [{
            name: '销售额',
            type: 'line',
            smooth: true,
            data: chartData.map(item => item.value),
            itemStyle: {
                color: '#1890ff'
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(24,144,255,0.3)'
                }, {
                    offset: 1,
                    color: 'rgba(24,144,255,0.1)'
                }])
            }
        }]
    };

    myChart.setOption(option);

    // 监听窗口大小变化
    window.addEventListener('resize', function() {
        myChart.resize();
    });
}
// 修改下拉框事件监听
document.addEventListener('DOMContentLoaded', function() {
    const trendSelect = document.querySelector('#trendSelect');
    if (trendSelect) {
        // 设置默认选项
        trendSelect.innerHTML = `
            <option value="近1周">近1周</option>
            <option value="上一周">上一周</option>
            <option value="近1月">近1月</option>
        `;

        trendSelect.addEventListener('change', function(e) {
            const selectedPeriod = e.target.value;
            // 现在 fetchUserData() 会返回 Promise
            fetchUserData().then(data => {
                updateDashboardData(data, selectedPeriod);
            }).catch(error => {
                console.error('更新数据失败:', error);
            });
        });
    }
});